package com.mapler.scrapper;

import com.mapler.ngfx.service.*;
import com.mapler.model.SModel;
import com.mapler.model.UAModel;
import com.mapler.service.INotifier;
import com.mapler.utility.EMailModel;
import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import com.mapler.utility.MailSubjectReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

/**
 *
 * @author none
 */
public class ScrapperClick implements Runnable {

    private SModel sModel;
    private static Logger log = Logger.getLogger(NGFXSignupClick.class);
    private INotifier iNotifier;
    private UAModel uAModel = new UAModel();
    MailSubjectReader mailSubjectReader;

    public ScrapperClick(INotifier iNotifier, SModel sModel) {
        this.sModel = sModel;
        this.iNotifier = iNotifier;
    }

    public ScrapperClick(SModel iModel) {
        this.sModel = iModel;
    }

    @Override
    public void run() {
        try {
            this.doPost();
            log.debug("Scrapper:Run::Done !!!");
        } catch (Throwable ex) {
            iNotifier.notify("Scrapper:Run:: stopped for error: " + ex.getMessage());
            log.error("Scrapper:Run:: stopped causes " + ex);
        }
    }

    private void doPost() {
        File file = null;
        BufferedWriter output = null;
        try {
            ArrayList<String> mailSubjects = this.getMailSubjectReader().checkMail();
            iNotifier.notify("Writing in file...");
            file = new File("c:\\irobot\\scrapper.csv");
            output = new BufferedWriter(new FileWriter(file, true));
            Pattern p = Pattern.compile("\\(\\d{3}\\)\\s\\d{3}-\\d{4}");
            int total = mailSubjects.size();
            int count = 0;
            List<String> numbers = new ArrayList<String>();
            for (String sub : mailSubjects) {
                if (StringUtils.isNotBlank(sub)) {
                    Matcher matcher = p.matcher(sub);
                    while (matcher.find()) {
                        output.newLine();
                        String subject = matcher.group();
                        subject = subject.replaceAll("\\(", "").replaceAll("\\)", "").replaceAll(" ", "").replaceAll("-", "").trim();
                        subject = "+1" + subject;
                        output.write(subject);
                        if (sModel.isStore()) {
                            numbers.add(subject);
                            //this.addScrapper(sModel, subject);
                        }
                        count = count + 1;
                        iNotifier.notify("Writing " + count + " of " + total);
                    }
                }
            }
            if (sModel.isStore()) {
                this.addScrapper(sModel, numbers);
            }
            iNotifier.notify("Writing into file done");
        } catch (Throwable ex) {
            ex.printStackTrace();
            iNotifier.notify("Scrapper:Run:: stopped for error: " + ex.getMessage());
            log.error("Scrapper:Run:: stopped causes " + ex);
        } finally {
            if (output != null) {
                try {
                    output.flush();
                    output.close();
                } catch (IOException ex) {
                    iNotifier.notify("Scrapper:Run:: stopped for error: " + ex.getMessage());
                    log.error("Scrapper:Run:: stopped causes " + ex);
                }
            }
        }
    }

    public void addScrapper(SModel m, List<String> numbers) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(m.getUsername()).append("</username>");
            request.append("<password>").append(m.getPassword()).append("</password>");
            request.append("<email>").append(m.getEmail()).append("</email>");
            request.append("<emailpassword>").append(m.getEmailPassword()).append("</emailpassword>");

            request.append("<numbers>");
            for (String number : numbers) {
                request.append("<number>").append(number).append("</number>");
            }
            request.append("</numbers>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=scrapper/addAccount";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            if (errorCode.equalsIgnoreCase("000")) {
                log.error("Scrapper:uploaded...");
            } else {
                log.error("Scrapper:Not work...");
            }
        } catch (Exception ex) {
            log.error("Scrapper:Run:: stopped causes " + ex);
            ex.printStackTrace();
        }
    }

    public MailSubjectReader getMailSubjectReader() {
        if (mailSubjectReader == null) {
            EMailModel em = new EMailModel();
            em.setEmail(sModel.getEmail());
            em.setEmailPassword(sModel.getEmailPassword());
            mailSubjectReader = new MailSubjectReader(em, iNotifier);
        }
        return mailSubjectReader;
    }

    public void setMailSubjectReader(MailSubjectReader mailSubjectReader) {
        this.mailSubjectReader = mailSubjectReader;
    }

    public static void main(String s[]) {
        try {
            Pattern p = Pattern.compile("\\(\\d{3}\\)\\s\\d{3}-\\d{4}");
            //String mm = "(804) 298-8353";
            String subject = "SMS from (412) 874-0718";
            Matcher matcher = p.matcher(subject);
            //subject = StringUtils.substringBetween(subject, "\\(\\d{3}\\)\\s\\d{3}-\\d{4}");  

            while (matcher.find()) {
                System.out.println("Match: " + matcher.group());
                return;
            }

            File file = new File("c:\\irobot\\scrapper.csv");
            BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
            output.write("\n");
            output.write("mithun");
            output.close();
        } catch (IOException ex) {
            java.util.logging.Logger.getLogger(ScrapperClick.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}